package service

import (
	"context"
	"fmt"

	pb "gitee.com/snitso/micro/api/example/v1"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	transgrpc "github.com/go-kratos/kratos/v2/transport/grpc"

	"google.golang.org/grpc"
)

type ExampleService struct {
	pb.UnimplementedExampleServer

	logger *log.Helper
}

func NewExampleService(logger log.Logger) *ExampleService {
	return &ExampleService{logger: log.NewHelper(logger)}
}

// SayHello is a server method for ExampleService.
// 如果调用 rpc 服务，一定要确保客户端和服务端的 proto 文件 package 一样，否则会报错：
// rpc error: code = Unimplemented desc = unknown service app.client.api.example.v1.Example
// 见 api/example/v1/example.proto
func (s *ExampleService) SayHello(ctx context.Context, req *pb.GetExampleRequest) (*pb.GetExampleReply, error) {
	conn, err := transgrpc.DialInsecure(
		context.Background(),
		transgrpc.WithEndpoint("127.0.0.1:9000"),
		transgrpc.WithMiddleware(
			recovery.Recovery(),
			tracing.Client(),
		),
	)
	if err != nil {
		return nil, err
	}
	defer func(conn *grpc.ClientConn) {
		_ = conn.Close()
	}(conn)
	client := pb.NewExampleClient(conn)
	reply, err := client.SayHello(context.Background(), &pb.GetExampleRequest{Name: req.Name})
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	s.logger.Infof("[grpc] SayHello %+v\n", reply)
	return &pb.GetExampleReply{
		Name: reply.Name,
	}, nil
}
